//local bcenterx = 160 - ((cum.width()/(cum.dupx() * 2) - 160))
//local bcentery = 100 + ((cum.height()/(cum.dupy() * 2) - 100)) 
/*CV_Rampage.icontable = {
	Ranger = "SONICICON",
	Doom = "DOOM1ICON",
	Doom1	= "DOOM1ICON",
	Doom2 = "DOOM2ICON",
	Quake = "Q1ICON",
	Quake1 = "Q1ICON",
	Quake2 = "Q2ICON",
	Quake3 = "Q3ICON",
	Super = "SUPERICON",
	Snoop = "WEEDICON",
	USA = "USAICON",
	Mental = "BOYKISSERSLOP",
	Bin = "PAINTEDNAILS",
	Nails = "PAINTEDNAILS",
	VVVVVV = "VVVVVVICON",
}

CV_Rampage.modestable = {
	Singleplayer = "Single",
	SP = "Single",
	Coop = "Coop",
	MP = "Coop",
	Multiplayer = "Coop",
	Match = "Deathmatch",
	DM = "Deathmatch",
	Deathmatch = "Deathmatch",
	Multiplayer = "Coop",
	TeamMatch = "TDM",
	TDM = "TDM",
	TeamDeathmatch = "TDM",
	CTF = "CTF",
	Capture = "CTF",
	CaptureTheFlag = "CTF",
	Flag = "CTF",
	TwoFlag = "CTF",
	Clan = "Clan Arena",
	ClanArena = "Clan Arena",
	Arena = "Clan Arena",
	CA = "Clan Arena",
	OneFlag = "1 Flag",
	OneCTF = "1 Flag",
}

CV_Rampage.mutatorstable = {
	None = "Normal",
	Normal = "Normal",
	Rocket = "Rocket",
	RocketArena = "Rocket",
	RA = "Rocket",
	Insta = "InstaGib",
	InstaGib = "InstaGib",
	IG = "InstaGib",
	Close = "C. Quarters",
	CloseQuarters = "C. Quarters",
	CQ = "C. Quarters",
}

local BLANKLICENSE = "0 0 0 0 0 0 Deathmatch Normal Ranger"

local function SaveLicense(p)
	local IsPlayerLicenseValid = (not ((p.licensewins == nil)
		or (p.licenseloses == nil)
		or (p.licensekills == nil)
		or (p.licensekstreak == nil)
		or (p.licensecaps == nil)
		or (p.licensecstreak == nil)
		or (p.licensemode == nil)
		or (p.licensemutator == nil)
		or (p.licenseicon == nil)))

	if IsPlayerLicenseValid then
		local file = io.openlocal("client/rampage/LICENSEDATA.dat", "w+")//open up our file, in write mode this time
		file:seek("set")//set our position to the start of the file just incase
		file:write(tostring(p.licensewins.." "..p.licenseloses.." "..p.licensekills.." "..p.licensekstreak.." "..p.licensecaps.." "..p.licensecstreak.." "..p.licensemode.." "..p.licensemutator.." "..p.licenseicon))//write the data to the file
		
		file:close()//CLOSE THE DAMN DOOR
		CONS_Printf(p, "Your license was successfully saved!")
	elseif not IsPlayerLicenseValid then
		CONS_Printf(p, "Could not verify license data!! Cannot write to license!!")
	end
end

local function GetPlayer(pname)
	if not pname then return end

	if tonumber(pname) then
		if (players[pname].valid and players[pname].mo.valid) then
			return players[pname]
		end
	end
	if tostring(pname) then
		for player in players.iterate do
			if player.name == pname then 
				if (player.valid and player.mo.valid) then//the hell "if" nest of torture and dispair
					return player
				end
			end
		end
	end
end

local function hairyballs(str)
	if str=="" then return end
	local first = string.sub(str, 1,1)
	local last = string.sub(str, 2)
	return string.upper(first)..string.lower(last)
end

local istolethisfromtakislol = "iamlua"..P_RandomFixed()//lets make a checksum for the command to stop you from just uploading your own license icon data by hand.

COM_AddCommand("licensetokill", function (p, alcohol, ...)//command for uploading our file, this allows us to upload that local data from earlier using COM_BUFInsertText, which sends stuff as a command the same way a player would but while also allowing us to access lua variables and such.
	if not alcohol then//check if we even have a checksum, if not then throw out an error.
		CONS_Printf(p, "NO CHECKSUM GIVEN, PLEASE DO NOT USE THE 'licensetokill' COMMAND MANUALLY")
		return//end our function early.
	end
	if alcohol ~= istolethisfromtakislol then//check if our uploaded checksum matches the randomly generated checksum from earlier, if not throw out a DIFFERENT error.
		CONS_Printf(p, "CHECKSUM CANNOT BE VERIFIED, PLEASE DO NOT USE THE 'licensetokill' COMMAND MANUALLY")
		return//end our function early.
	end
	local commandlicensetable = {...}//turn that string of numbers from earlier into a table like we said.
	
	if commandlicensetable == nil then//check for nil specifically because this can be 0
		CONS_Printf(p, "NO LICENSE DATA GIVEN, FAILED TO LOAD OR CREATE NEW LICENSE DATA")
		CONS_Printf(p, "IF PROBLEM PERSISTS A BLANK LICENSE CAN BE OBTAINED FROM [download not yet available]")
		CONS_Printf(p, "IT SHOULD BE PLACED IN '[Your Srb2 folder here]/luafiles/client'")
		return
	end
	
	if ((commandlicensetable[10]) or (not commandlicensetable[9])) and (commandlicensetable[1]) then//check if our license information has too much or too little info, and there was an actual ATTEMPT to send license info (atleast 1 entry), likely because you're a fraud and failed to edit your license correctly, if so then PUNISH THE CRIMINAL
		CONS_Printf(p, "MALFORMED LICENSE INFORMATION, LICENSE FRAUD IS A CRIME!!!")
		P_DamageMobj(p.mo, 0, 0, 1, DMG_INSTAKILL)//instantly fucking kill this scumbag ID frauder, you fucking roach never show your face here again blech.
		//chatprint(p.name.." is a fucking license frauding SCUMBAG, GET HIM!!!!!", false)//publicly humiliate this loser
		S_StartSound(nil, sfx_bedie2)//scary ass brak noise for better measure, globally ofc
		return//fuck your fake license, we're ending the function here so your fake license isnt loaded
	end
	
	p.licensewins = tonumber(commandlicensetable[1])
	p.licenseloses = tonumber(commandlicensetable[2])
	p.licensekills = tonumber(commandlicensetable[3])
	p.licensekstreak = tonumber(commandlicensetable[4])
	p.licensecaps = tonumber(commandlicensetable[5])
	p.licensecstreak = tonumber(commandlicensetable[6])
	p.licensemode = tostring(commandlicensetable[7])
	p.licensemutator = tostring(commandlicensetable[8])
	p.licenseicon = commandlicensetable[9]
	
	CONS_Printf(p, "Your license was successfully loaded!") //we're all good, tell the player that
end)

COM_AddCommand("ShowLicense", function (p, m)
	if p.licensetokill == nil then
		p.licensetokill = 1
		p.licensepage = 1
	elseif p.licensetokill == 0 then
		p.licensetokill = 1
		p.licensepage = 1
		if GetPlayer(m) then
			p.licensereference = GetPlayer(m)
		else
			p.licensereference = p
		end
	else
		p.licensetokill = 0
		p.licensepage = nil
	end
end)

COM_AddCommand("LicenseIcon", function (p, breh)
	if breh == nil then
		//unpack table here to list all icon names, srb2 fucking blows ass so ill do this later
		return
	end
	if CV_Rampage.icontable[breh] == nil then
		print("INVALID ICON NAME!")
		return
	end
	if breh == "Mental" then
		chatprintf(p, "Why would you want this? I mean, I won't judge or anything.", false)//when the ඞ
		S_StartSound(p.mo, sfx_KILHIM, p)
	end
	if not (breh == nil) then
		p.licenseicon = breh
	end
end)

COM_AddCommand("FavoriteMode", function (p, brah, brih)
	if brah == nil then
		//unpack table here to list all icon names, srb2 fucking blows ass so ill do this later
		return
	end
	if CV_Rampage.modestable[brah] == nil then
		print("INVALID GAMEMODE!")
		return
	end
	if not (brah == nil) then
		p.licensemode = brah
	end
	if not (brih == nil) then
		if CV_Rampage.mutatorstable[brih] == nil then
			print("INVALID MUTATOR!")
		else
			p.licensemutator = brih
		end
	end
end)

COM_AddCommand("SaveLicense", function (p)
	SaveLicense(p)
end)

local function istolethisfrommetroidprimehunters(v, p)

	//print(p.licensetokill)
	
	local rwins = 0
	local rloses = 0
	local rkills = "Unknown"
	local rkstreak = "Unknown"
	local rcaps = "Unknown"
	local rcstreak = "Unknown"
	local rmode = "Unknown"
	local rmutator = "Unknown"
	local ricon = Ranger
	local rtime = "Unknown"
	
	if p.licensereference then
		rwins = p.licensereference.licensewins //copy all of the info from p.licensereference (the guy we're viewing) to reference variables so we can safely write over any malformed data WITHOUT writing over the player's actual stats.
		rloses = p.licensereference.licenseloses
		rkills = p.licensereference.licensekills
		rkstreak = p.licensereference.licensekstreak
		rcaps = p.licensereference.licensecaps
		rcstreak = p.licensereference.licensecstreak
		rmode = p.licensereference.licensemode
		rmutator = p.licensereference.licensemutator
		ricon = p.licensereference.licenseicon
		rtime = p.licensereference.timeinserver
	end
	
	local winrate = 0 //because locals can only be referenced up to the if they were referenced in for some stupid fucking reason
	
	if (rwins + rloses) > 0 then
		winrate = FixedInt((FixedDiv(rwins, (rwins + rloses)))*100)
	else
		winrate = "Unknown"
	end
	
	local bcenterx = 160 - ((v.width()/(v.dupx() * 2) - 160))
	local bcentery = 100 + ((v.height()/(v.dupy() * 2) - 100)) 
	
	local firekey = hairyballs(input.keyNumToName(input.gameControlToKeyNum(GC_FIRE)))
	local altfirekey = hairyballs(input.keyNumToName(input.gameControlToKeyNum(GC_FIRENORMAL)))

	if p.licensetokill == 1 then
		v.draw(bcenterx, bcentery, v.cachePatch("LICENSE0" .. p.licensepage), V_SNAPTOTOP|V_SNAPTORIGHT, v.getColormap(p.mo.skin, p.skincolor))
		v.draw(bcenterx+24, bcentery-16, v.cachePatch(CV_Rampage.icontable[ricon] or "SONICICON"), V_SNAPTOTOP|V_SNAPTORIGHT, v.getColormap(p.mo.skin, p.skincolor))//this should let you pick a custom color at some point.
		v.drawString(bcenterx - 68, bcentery+2, firekey, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "right")
		v.drawString(bcenterx + 68, bcentery+2, altfirekey, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "left")
		v.drawString(bcenterx, bcentery-72-4, p.licensereference.name, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "center")
		if p.licensepage == 1 then
			v.drawString(bcenterx - 20, bcentery-56+4, "Win rate", V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "center")
			v.drawString(bcenterx - 20, bcentery-48+4, winrate.."%", V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "center")
			v.drawString(bcenterx - 20, bcentery-32+4, "W/L Ratio", V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "center")
			v.drawString(bcenterx - 20, bcentery-24+4, rwins.."/"..rloses, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "center")
		elseif p.licensepage == 2 then
			v.drawString(bcenterx - 20, bcentery-56+4, "Total Kills", V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "center")
			v.drawString(bcenterx - 20, bcentery-48+4, rkills, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "center")
			v.drawString(bcenterx - 20, bcentery-32+4, "Killstreak", V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "center")
			v.drawString(bcenterx - 20, bcentery-24+4, rkstreak, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "center")
		elseif p.licensepage == 3 then
			v.drawString(bcenterx - 20, bcentery-56+4, "Total Caps", V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "center")
			v.drawString(bcenterx - 20, bcentery-48+4, rcaps, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "center")
			v.drawString(bcenterx - 20, bcentery-32+4, "Capstreak", V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "center")
			v.drawString(bcenterx - 20, bcentery-24+4, rcstreak, V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "center")
		elseif p.licensepage == 4 then
			v.drawString(bcenterx - 20, bcentery-56, "Favorite", V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "small-center")
			v.drawString(bcenterx - 20, bcentery-56+4, "Gamemode", V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "center")
			v.drawString(bcenterx - 20, bcentery-48+4, CV_Rampage.modestable[rmode] or "Deathmatch", V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "center")
			v.drawString(bcenterx - 20, bcentery-32, "Favorite", V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "small-center")
			v.drawString(bcenterx - 20, bcentery-32+4, "Mutator", V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "center")
			v.drawString(bcenterx - 20, bcentery-24+4, CV_Rampage.mutatorstable[rmutator] or "Normal", V_ALLOWLOWERCASE|V_SNAPTOBOTTOM|V_SNAPTORIGHT, "center")
		end
	end
end

hud.add(istolethisfrommetroidprimehunters, "game")

addHook("PlayerThink", function(p)
	if p.licensetokill == nil then
		p.licensetokill = 0
	end
	if p.licensetokill > 0 then
		p.pflags = $ | PF_FULLSTASIS
		if p.weapondelay == 0 then
			p.weapondelay = 1
		end
		if p.cmd.buttons & BT_ATTACK and not (p.lastbuttons & BT_ATTACK) then
			p.licensepage = $ - 1
			if p.licensepage < 1 then
				p.licensepage = 4
			end
		end
		if p.cmd.buttons & BT_FIRENORMAL and not (p.lastbuttons & BT_FIRENORMAL) then
			p.licensepage = $ + 1
			if p.licensepage > 4 then
				p.licensepage = 1
			end
		end
	end
end)

//little guide for all the noobies reading this code for help with them using io.openlocal for their own saving stuff.
rawset(_G, "LoadLicenseData", function(p) //heres the start of the function to unpack and upload our license data to the server.
	local file = io.openlocal("client/rampage/LICENSEDATA.dat") //we set file as an alias to the file "LICENSEDATA.dat".
	local datatable
	if p ~= consoleplayer then return end
	if file then//check if we actually have anything after reading the file, if the file doesn't exist or is empty then it will return nil, so we don't want to try uploading non-existant data.
		file:seek("set") //set the "current position" (where we start reading from) to the very beginning of the file, you know, *just incase.*
		datatable = file:read("*a")//we set "datatable" to all of the stuff we can read in the file (*a reads everything from the "current position"). Also note, "datatable" will actually be a string, not a table, io.open and io.openlocal only allow saving of strings and integers, we'll convert this string to a table later in our command.
		CONS_Printf(p, "Loading your license...")//debug message
		COM_BufInsertText(consoleplayer, "licensetokill "..istolethisfromtakislol.." "..datatable)//use the command we made at the top of the script to upload this data to the server, io.openlocal only opens a file LOCALLY so if we attempted to use the data right now it'd desync the game.
	end
	if not file then//could probably just use an else here but again I'm trying to be safe with handling the player's data here, so we're checking again to be double sure, check if we don't actually have the file/theres no data in the file.
		CONS_Printf(p, "No existing 'Arena license' data could be found.")//print shit here
		CONS_Printf(p, "An 'Arena license' will be issued to you immediately.") //making these seperate functions prints these as seperate lines.
		CONS_Printf(p, "Your license will be saved at the end of multiplayer matches.")
		COM_BufInsertText(consoleplayer, "licensetokill "..istolethisfromtakislol.." "..BLANKLICENSE)//insert a blank license card for the data
	end
	
	if file then//make sure we have a file to actually close in the first place.
		file:close()//make sure we close the file before ending our function!
	end
end)//end of function

addHook("PlayerThink", function(p)
	if not p.licensedataloaded then//if we haven't loaded out data yet then run the procedure
		p.licensedataloaded = 1//give us an identifier that we've loaded the data for the above line
		LoadLicenseData(p)//run the function we wrote earlier
	end
	
	if p.currentkstreak == nil then
		p.currentkstreak = 0
	end
	if p.currentcstreak == nil then
		p.currentcstreak = 0
	end
	if p.currentkstreak > p.licensekstreak then
		p.licensekstreak = p.currentkstreak
		chatprintf(p, "You've pushed your top killstreak up!")
	end
	if p.currentcstreak > p.licensecstreak then
		p.licensecstreak = p.currentcstreak
		chatprintf(p, "You've pushed your top capstreak up!")
	end
	
	if p.fucknuts == nil then //completely unrelated to what we're doing, this just gets another error message to shut the fuck up
		p.fucknuts = 0
	end
end)


//Below is the hooks for updating player stats


addHook("MobjDeath", function(guy, jeffthe, normalperson)
	if not guy.player and guy.player.valid then return end //dont track kills on non-player enemies
		guy.player.currentkstreak = 0
		guy.player.currentcstreak = 0
	if normalperson.player and normalperson.valid then
		normalperson.player.licensekills = $ + 1
		normalperson.player.currentkstreak = $ + 1
	end
end, MT_PLAYER)

local intermissionstatcalc = 0
local winningteam = 0
local bestplayer = 0

addHook("IntermissionThinker", function()
	if (gametyperules & GTR_CAMPAIGN) or (gametyperules & GTR_FRIENDLY) then return end//don't stat track cooperative modes
	if intermissionstatcalc ~= 0 then return end//don't add wins if we've already done calculations this intermission
	if gametyperules & GTR_TEAMS then //tell who wins in team games
		if bluescore > redscore then // blue wins
			winningteam = 2 //punish red
		elseif redscore > bluescore then //red wins
			winningteam = 1 //punish blue
		elseif bluescore == redscore then //tie
			winningteam = 0 //fuck you all, you all lose, you all take the punishment
		end
		for player in players.iterate do
			if player.ctfteam == winningteam then
				player.licensewins = $ + 1
			else
				player.licenseloses = $ + 1
			end
		end
	elseif gametyperules & ~GTR_TEAMS then //tell who wins in non-team games
		bestplayer = server
		for player in players.iterate do //doesn't check for tying, but this is literally impossible with 90% of rulesets, plus i dont think people care about W/L that much anyways xd
			if player.score > bestplayer.score then
				bestplayer = player
			end
		end
		for player in players.iterate do
			if player == bestplayer then
				player.licensewins = $ + 1 
			elseif player ~= bestplayer
				player.licenseloses = $ + 1
			end
		end
	end
	
	for player in players.iterate do //we've done all our stat calculations, save the licenses now.
		SaveLicense(player)
	end
	
	intermissionstatcalc = 1
end)

addHook("MapLoad", function()
	intermissionstatcalc = 0 //literally just reset this variable lol
end)

addHook("GameQuit", function()
	SaveLicense(consoleplayer)//QUICK! EMERGENCY SAVE BEFORE THE GAME FUCKING DIES RAGHHH!!!
end)